
from flask import Blueprint, render_template, request, current_app

from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, success_api, fail_api
from applications.common.utils.validate import xss_escape
from applications.models import CourseStandard, ActionInfo, KeyframeInfo, StandardResult, PoliceModels
from applications.schemas import StandardSchema, ActionSchema, KeyframeInfoSchema, PoliceOutSchema, StandardResultSchema, ConfrontationReportSchema
from applications.common.utils.http import success_api, fail_api
from applications.extensions import db
from applications.models import ConfrontationReport, PoliceModels

training_bp = Blueprint('training', __name__, url_prefix='/training')


@training_bp.post('/report')
def receive_report():
    try:
        codes = request.args['UserID']
        result = bool(request.args['Result'])
        total_time = float(request.args['TotalTime'])
        score = float(request.args['Score'])
        training_name = request.args['TrainingType']
    except:
        return fail_api()
    for code in codes.split(','):
        police = PoliceModels.query.filter_by(code=code).one_or_none()
        if police is not None:
            report = ConfrontationReport(user_id=police.id,
                                         result=result,
                                         total_time=total_time,
                                         training_name=training_name,
                                         score=score)
            db.session.add(report)
        else:
            return fail_api()
    db.session.commit()
    return success_api()


@training_bp.get('/result')
def getResultPage():
    return render_template('admin/scene/score.html')

@training_bp.get('/result/detail/<int:user_id>')
def result_details(user_id):
    # 获取请求参数
    results = ConfrontationReport.query.filter_by(user_id=user_id).layui_paginate()
    results_dict = model_to_dicts(schema=ConfrontationReportSchema, data=results.items)
    count = results.total
    return render_template('admin/scene/score_detail.html', data=results_dict, count=count)
